package com.rzico.sbl.ui.statistic

import android.widget.TextView
import androidx.core.view.isVisible
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityStockStoreBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.FilterData
import com.rzico.sbl.model.StoreData
import com.rzico.sbl.other.getBeforeDate
import com.rzico.sbl.other.getBeforeEndDate
import com.rzico.sbl.other.getBeforeFirstDate
import com.rzico.sbl.other.getEndDate
import com.rzico.sbl.other.getFirstDate
import com.rzico.sbl.other.getMondayDate
import com.rzico.sbl.other.getSundayDate
import com.rzico.sbl.other.getTodayDate
import com.rzico.sbl.other.getYearEndDate
import com.rzico.sbl.other.getYearFirstDate
import com.rzico.sbl.viewmodel.StatisticStockViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.condition
import com.xinnuo.common.extend.conditionElse
import com.xinnuo.common.extend.conditionFalse
import com.xinnuo.common.extend.conditionIf
import com.xinnuo.common.extend.find
import com.xinnuo.common.extend.formatDecimal
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.getColorEx
import com.xinnuo.common.extend.gone
import com.xinnuo.common.extend.goneValue
import com.xinnuo.common.extend.notEmpty
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.extend.optNotNull
import com.xinnuo.common.extend.orEmpty
import com.xinnuo.common.extend.startActivityEx
import com.xinnuo.common.extend.visibleValue
import com.xinnuo.common.helper.bottomHide
import com.xinnuo.common.helper.bottomShow
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.listener.onTabSelectedListener
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.utils.addOnScrollChanged
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.showTimeRangeDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONObject

class StockStoreActivity : BaseActivity(R.layout.activity_stock_store) {

    private val mBinding by lazy { ActivityStockStoreBinding.bind(getRootView()) }

    private val mShopList = arrayListOf<FilterData>()
    private val mSupplyList = arrayListOf<FilterData>()
    private var mStatus = ""
    private var mShopId = ""
    private var mSupplyId = ""
    private var mBeginDate = ""
    private var mEndDate = ""

    override fun getViewModel() = get<StatisticStockViewModel>()

    override fun initData() {
        initTitle(title = "采购入库")

        initLayout()
        initTabLayout()
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout
                    .emptyHint
                    .text = "暂无相关采购单信息！"

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = {
                            orderCount()
                            getData(0)
                        },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    layout.addItemDecoration(SpaceTBDecoration(hasHeader = false, bottom = 60f))
                    layout.addOnScrollChanged(
                        onShow = { mBinding.storeBottom.bottomShow() },
                        onHide = { mBinding.storeBottom.bottomHide(55f) }
                    )

                    mAdapter = SlimAdapter.creator()
                        .register<StoreData>(R.layout.item_stock_store) { jector, bean, _ ->
                            jector.apply {
                                text(R.id.item_store_time, bean.createDate.getTimeString())
                                text(R.id.item_store_statu, bean.statusDescr)
                                text(R.id.item_store_supply, bean.supplier)
                                text(R.id.item_store_shop, bean.shopName)
                                text(R.id.item_store_count, bean.subQuantity)
                                text(R.id.item_store_price, bean.amount.formatDecimal())
                                text(R.id.item_store_operator, bean.operator)
                                text(R.id.item_store_memo, bean.memo)

                                visibility(
                                    R.id.item_store_memo_ll,
                                    goneValue { bean.memo.isNullOrEmpty() }
                                )

                                visibility(
                                    R.id.item_store_btn_ll,
                                    visibleValue { bean.status == "debit" }
                                )

                                clicked(R.id.item_store_btn1) {
                                    confirmStore(bean.id)
                                }

                                clicked(R.id.item_store_btn2) {
                                    startActivityEx<StockStoreEditActivity>(
                                        "title" to "入库编辑",
                                        "mode" to "edit",
                                        "storeId" to bean.id
                                    )
                                }

                                clicked {
                                    (bean.status == "credit")
                                        .condition {
                                            startActivityEx<StockStoreDetailActivity>(
                                                "storeId" to bean.id
                                            )
                                        }
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }
    }

    /**
     * 初始化 TabLayout
     */
    private fun initTabLayout() {
        mBinding
            .storeTab
            .apply {
                onTabSelectedListener {
                    onTabSelected {
                        it?.let {
                            mStatus = when (it.position) {
                                1 -> "debit"
                                2 -> "credit"
                                else -> ""
                            }

                            mBinding
                                .storeBottom
                                .bottomShow()

                            getViewModel().cancelRequest()
                            getViewModel().delay { updateList() }
                        }
                    }
                }

                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "全部"
                    },
                    true
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "待入库"
                    },
                    false
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "已入库"
                    },
                    false
                )
            }
    }

    override fun initListener() {
        mBinding.apply {
            storeSupplyLl.oneClick {
                getSupplyList {
                    getViewModel()
                        .showDropFilter(
                            getIContext(),
                            storeTop,
                            mSupplyList,
                            storeSupply,
                            storeSupplyArrow
                        ) { bean ->
                            storeSupply.setTextColor(
                                getColorEx(
                                    conditionIf(
                                        bean.id.isEmpty(),
                                        R.color.black,
                                        R.color.colorAccent
                                    )
                                )
                            )

                            storeSupplyArrow.setImageResource(
                                conditionIf(
                                    bean.id.isEmpty(),
                                    R.mipmap.icon_member01,
                                    R.mipmap.icon_member02
                                )
                            )

                            mSupplyId = bean.id

                            updateList()
                        }
                }
            }

            storeShopLl.oneClick {
                getShopList {
                    getViewModel()
                        .showDropFilter(
                            getIContext(),
                            storeTop,
                            mShopList,
                            storeShop,
                            storeShopArrow
                        ) { bean ->
                            storeShop.setTextColor(
                                getColorEx(
                                    conditionIf(
                                        bean.id.isEmpty(),
                                        R.color.black,
                                        R.color.colorAccent
                                    )
                                )
                            )

                            storeShopArrow.setImageResource(
                                conditionIf(
                                    bean.id.isEmpty(),
                                    R.mipmap.icon_member01,
                                    R.mipmap.icon_member02
                                )
                            )

                            mShopId = bean.id

                            updateList()
                        }
                }
            }

            storeTimeLl.oneClick {
                getViewModel()
                    .showDropTimeFilter(
                        getIContext(),
                        storeTime,
                        storeTimeArrow,
                        storeTop,
                        getViewModel().timeList
                    ) { bean ->

                        (bean.id != "7")
                            .condition {
                                getViewModel()
                                    .timeList
                                    .last()
                                    .name = "自定义时间"
                            }

                        when (bean.id) {
                            "0" -> {
                                mBeginDate = ""
                                mEndDate = ""

                                updateList()
                            }

                            "1" -> {
                                mBeginDate = getTodayDate()
                                mEndDate = getTodayDate()

                                updateList()
                            }

                            "2" -> {
                                mBeginDate = getBeforeDate()
                                mEndDate = getBeforeDate()

                                updateList()
                            }

                            "3" -> {
                                mBeginDate = getMondayDate()
                                mEndDate = getSundayDate()

                                updateList()
                            }

                            "4" -> {
                                mBeginDate = getFirstDate()
                                mEndDate = getEndDate()

                                updateList()
                            }

                            "5" -> {
                                mBeginDate = getBeforeFirstDate()
                                mEndDate = getBeforeEndDate()

                                updateList()
                            }

                            "6" -> {
                                mBeginDate = getYearFirstDate()
                                mEndDate = getYearEndDate()

                                updateList()
                            }

                            "7" -> {
                                showTimeRangeDialog(
                                    isCurrentDate = true,
                                    isAfterLimited = true,
                                    onResult = { start, end ->
                                        getViewModel()
                                            .timeList
                                            .forEach { it.isChecked = false }

                                        getViewModel()
                                            .timeList
                                            .last()
                                            .isChecked = true

                                        mBeginDate = start
                                        mEndDate = end
                                        bean.name = "$mBeginDate ~ $mEndDate"
                                        storeTime.text = bean.name

                                        updateList()
                                    }
                                )
                            }
                        }
                    }
            }

            storeAdd.oneClick {
                startActivityEx<StockStoreEditActivity>(
                    "title" to "添加入库",
                    "mode" to "add"
                )
            }
        }

        observe<String>("storeList") { updateList() }
    }

    /**
     * 确认入库
     */
    private fun confirmStore(storeId: String) {
        showHintDialog(
            hint = "确定要商品入库吗？",
            onSure = {
                getViewModel()
                    .requestBind(
                        requestUrl = BaseUrl.psiStoreCrm,
                        params = arrayOf("id" to storeId)
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("入库成功！")

                            updateList()
                        }
                    )
            }
        )
    }

    /**
     * 获取店铺列表，含自提点
     */
    private fun getShopList(onNext: () -> Unit) {
        mShopList
            .isNotEmpty()
            .conditionElse(
                actionTrue = onNext,
                actionFalse = {
                    getViewModel()
                        .shopList(
                            onSuccess = { list ->
                                mShopList.clear()

                                mShopList.add(
                                    FilterData("全部", "", "仓库", true)
                                )

                                list.notEmpty {
                                    mapTo(mShopList) {
                                        FilterData(
                                            it.shopName.orEmpty(),
                                            it.id,
                                            it.shopName.orEmpty()
                                        )
                                    }
                                }
                            },
                            onFinally = onNext
                        )
                }
            )
    }

    /**
     * 获取供应商列表
     */
    private fun getSupplyList(onNext: () -> Unit) {
        mSupplyList
            .isNotEmpty()
            .conditionElse(
                actionTrue = onNext,
                actionFalse = {
                    getViewModel()
                        .supplyList(
                            page = 0,
                            pageSize = 100,
                            isLoading = true,
                            onSuccess = { body ->
                                mSupplyList.clear()

                                mSupplyList.add(
                                    FilterData("全部", "", "供应商", true)
                                )

                                body.data.notEmpty {
                                    mapTo(mSupplyList) {
                                        FilterData(
                                            it.name.orEmpty(),
                                            it.id,
                                            it.name.orEmpty()
                                        )
                                    }
                                }
                            },
                            onFinally = onNext
                        )
                }
            )
    }

    /**
     * 更新自定义Tab数量
     */
    private fun orderCount() {
        getViewModel()
            .orderCount()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    val obj = JSONObject(it)
                    getViewModel()
                        .updateNum(
                            obj.optNotNull("debit"),
                            mBinding.storeTab
                        )
                }
            )
    }

    /**
     * 采购列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .storeList(
                page = index,
                status = mStatus,
                shopId = mShopId,
                supplyId = mSupplyId,
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        orderCount()
        getData(0)
    }

}